package com.central.apps.handler;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.constant.AppConstant;
import com.central.app.service.HandlerService;
import com.central.apps.entity.CostAttribute;
import com.central.apps.entity.CostDetailAttribute;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.apps.service.CostAccumulationService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.o;

@Slf4j
@Component
public class ItemapplyHandler extends LvBaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private CostAccumulationService costAccumulationService;

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("itemapplyApp".equals(app)){
            if ("getitemapplynum".equals(type)){
                String glnum = MapUtils.getString(params, "glnum");
                Map<String, Object> map = handlerService.findOneBySql(" select location from gq_itemapply where itemapplynum = '" + glnum + "'");
                if (map != null && !map.isEmpty()){
                    String location = MapUtils.getString(map, "location");
                    int page = 1;
                    int limit = 10;
                    if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                        page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                        limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                    }
                    return handlerService.pageList(page,limit,"SELECT\n" +
                            "\ta.itemnum,\n" +
                            "\ta.itemdesc,\n" +
                            "\ta.storenum,\n" +
                            "\ta.avblbalance,\n" +
                            "\ta.curbal,\n" +
                            "\ta.binnum,\n" +
                            "\ta.batchnum,\n" +
                            "\ta.unitcost \n" +
                            "FROM\n" +
                            "\tgq_invbalances a \n" +
                            "WHERE\n" +
                            "\ta.storenum = '" + location + "'  and a.avblbalance>0\n" +
                            "\tAND ( a.itemnum, a.binnum, a.storenum, a.batchnum ) NOT IN (\n" +
                            "\tSELECT\n" +
                            "\t\tb.itemnum,\n" +
                            "\t\tb.binnum,\n" +
                            "\t\tb.locations AS storenum,\n" +
                            "\t\tb.lotnum AS batchnum \n" +
                            "\tFROM\n" +
                            "\t\tgq_itemapplyline b \n" +
                            "\tWHERE\n" +
                            "\t\tb.glnum = '" + glnum + "' \n" +
                            "\t) ");
                }
            }
        }
        return super.operate(app, type, params);
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        String msg ="";
        List<Map<String, Object>> bySql = handlerService.findBySql("select itemapplynum from gq_itemapply where id =" + id);
        String itemapplynum =MapUtils.getString(bySql.get(0),"itemapplynum");
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_itemapplyline  where glnum ='" + itemapplynum + "'");
        if(ToolUtil.isEmpty(bySql1)){
            msg ="子表数据为空,无法提交审批";
        }
        if(flowNode.getId().equals("fqr")){
            List<Map<String, Object>> bySql9 = handlerService.findBySql("select * from gq_itemapply where id =" + id);
            String itemapplynum1 =MapUtils.getString(bySql9.get(0),"itemapplynum");
            List<Map<String, Object>> bySql10 = handlerService.findBySql("select * from gq_itemapplyline where glnum ='" + itemapplynum1 + "'");
            if(CollectionUtils.isNotEmpty(bySql10)) {
                for (Map<String, Object> map : bySql10) {
                    //Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
                    Float quantity = MapUtils.getFloat(map, "quantity");
                     if (quantity==0f){
                        msg = "当前出库申请中存在申请数量为“0”的物料，请变更申请数据后再提交审批！";

                    }//                    if (grantqty<quantity){
//                        msg="领用物料未完全出库，请更改出库数量";
//                    }
                }
            }
            String iscenterstore = MapUtils.getString(bySql9.get(0), "iscenterstore");//流程标识（是否为中心库房）1：不是中心库房2：是中心库房
            String issonsubject = MapUtils.getString(bySql9.get(0), "issonsubject");//流程标识（子表课题号是否为科研课题号）1：不是科研课题好2：是科研课题号
            String collectout = MapUtils.getString(bySql9.get(0), "collectout");//是否计划外领用 collectout=1为计划外领用 collectout=0不是计划外领用
            String issonpricemany = MapUtils.getString(bySql9.get(0), "issonpricemany");//流程标识（子表单价是否有超过1万）1：不超过1万2：超过一万
            //1.不是中心库房的流程会走到库管员，放开出库数量
            //2.
                //是中心库房
                //子表课题号不为科研管理
                //不是计划外领用
                //金额不大于1万
            boolean isboole=false;
            if("1".equals(iscenterstore)){
                isboole = true;
            }
            if("2".equals(iscenterstore)&&"1".equals(issonpricemany)&&"1".equals(issonsubject)&&"0".equals(collectout)){
                isboole = true;
            }
            if(isboole){
                handlerService.findBySql("update gq_itemapply set state = '1' where id ='"+id+"'");
            }

        }else if (flowNode.getId().equals("sh")){
            List<Map<String, Object>> bySql9 = handlerService.findBySql("select * from gq_itemapply where id =" + id);
            String itemapplynum1 =MapUtils.getString(bySql9.get(0),"itemapplynum");
            List<Map<String, Object>> bySql10 = handlerService.findBySql("select * from gq_itemapplyline where glnum ='" + itemapplynum1 + "'");
            if(CollectionUtils.isNotEmpty(bySql10)) {
                List<Map<String, Object>> bySql3 = handlerService.findBySql("SELECT * from biz_attribute where object_id=(SELECT id from biz_object where name ='gq_itemapplyline') and required !=''");
                if (CollectionUtils.isNotEmpty(bySql3)){
                    for(int i=0;i<bySql3.size();i++){
                        Map<String, Object> map = bySql3.get(i);
                        String required = MapUtils.getString(map, "required");
                        if (required!=null||required!=""){
                            //log.info("required+++++++++++++++++++++++++++++++++++++" + required);
                            String columnname = MapUtils.getString(bySql3.get(i), "columnname");
                            // log.info("required+++++++++++++++++++++++++++++++++++++" + columnname);
                            List<Map<String, Object>> bySql4 = handlerService.findBySql("select "+columnname+" from gq_itemapplyline where glnum='" + itemapplynum1 + "'");
                            if (CollectionUtils.isNotEmpty(bySql4)){
                                Map<String, Object> map1 = bySql4.get(0);
                                String columnname1 = MapUtils.getString(map1, columnname);
                                log.info("o+++++++++++++++++++++++++++++++++++++" + o);
                                if (StringUtils.isEmpty(columnname1)){
                                    log.info("required+++++++++++++++++++++++++++++++++++++" + columnname1);
                                    return "有必填信息未填，请继续填写!";
                                }else {
                                    log.info("required+++++++++++++++++++++++++++++++++++++" + columnname1);
                                }
                            }
                        }
                    }
                }
                for (Map<String, Object> map : bySql10) {
                    Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
                    String lotnum = MapUtils.getString(map, "lotnum");//批次
                    String itemnum = MapUtils.getString(map, "itemnum");
                    String binnum = MapUtils.getString(map, "binnum");//货位

//                    Float quantity = MapUtils.getFloat(map, "quantity");
                    if (grantqty == 0f) {
                        //流程后怎样抛出提示
                        msg = "当前出库申请中存在领料数量为“0”的物料，请变更领料数据后再提交审批！";
                    }
//                    lse if (quantity==0f){
//                        msg = "当前出库申请中存在领料数量为“0”的物料，请变更领料数据后再提交审批！";
//
//                    }//                    if (grantqty<quantity){
//                        msg="领用物料未完全出库，请更改出库数量";
//                    }
                }
//                for (int z=0;z<bySql10.size();z++){
//                    Map<String, Object> map = bySql10.get(z);
//                    Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
//                    Float avblbalance = MapUtils.getFloat(map, "avblbalance");
//                    String itemnum = MapUtils.getString(map, "itemnum");
//                    String lotnum = MapUtils.getString(map, "lotnum");
//                    float grantqty1=0;
////                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select t.* from gq_itemapplyline t left join gq_itemapply a on t.glnum=a.itemapplynum where t.itemnum='" + itemnum + "' and t.lotnum='" + lotnum + "' and a.status!='已核准'");
////                    if (CollectionUtils.isNotEmpty(bySql2)){
////                        for (int j=0;j<bySql2.size();j++){
////                            Map<String, Object> map1 = bySql2.get(j);
////                            Float grantqty2 = MapUtils.getFloat(map1, "GRANTQTY");
////                            grantqty1=grantqty1+grantqty2;//出库子表的出库总数量90
////                        }
////                    }
//                    //查询不为审批中的物料
//                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select t.* from gq_itemapplyline t left join gq_itemapply a on t.glnum=a.itemapplynum where t.itemnum='" + itemnum + "' and t.lotnum='" + lotnum + "'and a.status!='审批中'");
//                    if (CollectionUtils.isNotEmpty(bySql4)){
//                        for (int v=0;v<bySql4.size();v++){
//                            Map<String, Object> map1 = bySql4.get(v);
//                            Float grantqty2 = MapUtils.getFloat(map1, "GRANTQTY");
//                            grantqty1=grantqty1+grantqty2;
//                        }
//                        grantqty=grantqty+grantqty1;
//                        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "' and batchnum='" + lotnum + "'");
//                        Float avblbalance1 =(float)0;
//                        if (CollectionUtils.isNotEmpty(bySql5)){
//                            Map<String, Object> map1 = bySql5.get(0);
//                            avblbalance1 = MapUtils.getFloat(map1, "avblbalance");
//                        }
//                        List<Map<String, Object>> bySql6 = handlerService.findBySql("select t.* from gq_itemapplyline t left join gq_itemapply a on t.glnum=a.itemapplynum where t.itemnum='" + itemnum + "' and t.lotnum='" + lotnum + "' and a.status!='已核准'");
//                        if (CollectionUtils.isNotEmpty(bySql6)){
//                            List<Map<String, Object>> bySql7 = handlerService.findBySql("select t.* from gq_itemapplyline t left join gq_itemapply a on t.glnum=a.itemapplynum where t.itemnum='" + itemnum + "' and t.lotnum='" + lotnum + "'and a.status!='新建' and  a.status!='草稿' and a.status!='已核准'");
//                            if(CollectionUtils.isNotEmpty(bySql7)){
//                                float quantity3=0;
//                                for (int l=0;l<bySql7.size();l++){
//                                    Map<String, Object> map1 = bySql7.get(l);
//                                    Float grantqty2 = MapUtils.getFloat(map1, "GRANTQTY");
//                                    quantity3=quantity3+grantqty2;
//                                }
//                                avblbalance1=avblbalance1-quantity3;
//                                Float grantqty4 = MapUtils.getFloat(map, "GRANTQTY");
//                                if (avblbalance1.compareTo(grantqty4)<0){
//                                    int y = z + 1;
//                                    return "出库物料第"+y+"条数据中部分物料被人占用，当前库存剩余"+avblbalance1+"，请重新选择物料！";
//                                }
//                            }else if (CollectionUtils.isEmpty(bySql7)){
//                                Float grantqty4 = MapUtils.getFloat(map, "GRANTQTY");
//                                if (avblbalance1.compareTo(grantqty4)<0){
//                                    int y = z + 1;
//                                    return "出库物料第"+y+"条数据中部分物料被人占用，当前库存剩余"+avblbalance1+"，请重新选择物料！";
//                                }
//                            }
//                        }else {
//                            if (avblbalance1.compareTo(grantqty)<0){
//                                int y = z + 1;
//                                float avblbalance2=avblbalance1-grantqty1;
//                                BigDecimal bigDecimal = new BigDecimal(avblbalance2);
//                                bigDecimal=bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
//                                return "出库物料第"+y+"条数据中部分物料被人占用，当前库存剩余"+bigDecimal+"，请重新选择物料！";
//                                //return "出库物料第" + y + "条数据中物料库存剩余"+avblbalance2+",请重新选择物料！";
//                            }
//                        }
//
//                    }
//                }
                List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                if(CollectionUtils.isNotEmpty(sys_setting)) {
                    String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                    if (field8.equals("1")) {
                        for (int z=0;z<bySql10.size();z++) {
                            Map<String, Object> map = bySql10.get(z);
                            Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
                            //Float avblbalance = MapUtils.getFloat(map, "avblbalance");
                            String itemnum = MapUtils.getString(map, "itemnum");
                            String lotnum = MapUtils.getString(map, "lotnum");
                            String binnum = MapUtils.getString(map, "binnum");
                            String location = MapUtils.getString(bySql9.get(0), "location");
                            String subjectno = MapUtils.getString(bySql9.get(0), "subjectno");
                            String applicantid = MapUtils.getString(bySql9.get(0), "applicantid");//申请人
                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "' and batchnum='" + lotnum + "' and storenum='" + location + "' and subjectno='"+subjectno+"' and binnum='"+binnum+"'");
                            if(CollectionUtils.isNotEmpty(bySql2)){
                                Float avblbalance = MapUtils.getFloat(bySql2.get(0), "avblbalance");
                                String id1 = MapUtils.getString(bySql2.get(0), "id");
//                                String occurecords = MapUtils.getString(bySql2.get(0), "occurecords");//占用记录
                                Float numusage=(float) 0;
////                                String[] keyValuePairs = occurecords.split(", ");//将拼接后的字符串以适当的分隔符进行拆分
////                                for (String keyValuePair : keyValuePairs) {
////                                    String[] keyValue = keyValuePair.split(": ");
////                                    String key = keyValue[0];
////                                    String value = keyValue[1];
////                                    String cleanedStr = value.replace(",", "");
////                                    Float numusage1 = Float.valueOf(cleanedStr);
////                                    if (key.equals(applicantid)){
////                                        numusage=numusage+numusage1;
////                                    }
////                                }
                                List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_occurecords where invbalancesid='" + id1 + "' and applyby='"+applicantid+"'");
                                if (CollectionUtils.isNotEmpty(bySql4)){
                                    for (int i=0;i<bySql4.size();i++){
                                        Float numusage1 = MapUtils.getFloat(bySql4.get(i), "numusage");
                                        numusage=numusage+numusage1;
                                    }
                                }
                                avblbalance=avblbalance+numusage;//占用总数量和可用于量总数量之和
                                if (avblbalance.compareTo(grantqty)<0){
                                    int y = z + 1;
                                    return "出库物料第"+y+"条数据中部分物料被人占用，当前库存剩余"+avblbalance+"，请重新选择物料！";
                                }
                            }
                        }
                    }else {
                        for (int z=0;z<bySql10.size();z++){
                            Map<String, Object> map = bySql10.get(z);
                            Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
                            //Float avblbalance = MapUtils.getFloat(map, "avblbalance");
                            String itemnum = MapUtils.getString(map, "itemnum");
                            String lotnum = MapUtils.getString(map, "lotnum");
                            String binnum = MapUtils.getString(map, "binnum");
                            String location =MapUtils.getString(bySql9.get(0),"location");
                            String subjectno =MapUtils.getString(bySql9.get(0),"subjectno");
                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "' and batchnum='" + lotnum + "' and storenum='" + location + "' and subjectno='"+subjectno+"' and binnum='"+binnum+"'");
                            if (CollectionUtils.isNotEmpty(bySql2)){
                                Float avblbalance = MapUtils.getFloat(bySql2.get(0), "avblbalance");
                                if (avblbalance.compareTo(grantqty)<0){
                                    int y = z + 1;
                                    return "出库物料第"+y+"条数据中部分物料被人占用，当前库存剩余"+avblbalance+"，请重新选择物料！";
                                }
                            }
                        }
                    }
                }

            }

        }
//        else if (flowNode.getId().equals("fqr")){
//            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_itemapplyline where glnum ='" + itemapplynum + "'");
//            if (CollectionUtils.isNotEmpty(bySql2)){
//                for (int i=0;i<bySql2.size();i++){
//                    Map<String, Object> map = bySql2.get(i);
//                    Float quantity = MapUtils.getFloat(map, "quantity");
//                    Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
//                    if (quantity>grantqty){
//                        return "领用物料未完全出库，请更改出库数量";
//                    }
//                }
//            }
//        }

        return msg;
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if(flowNode.getId().equals("sh")){
            boolean flag =op.isFlag();
            if(flag){
                /*
                领料申请走完流程-->出库单
                 */
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_itemapply where id =" + id);
                String description =MapUtils.getString(bySql.get(0),"description");
                String location =MapUtils.getString(bySql.get(0),"location");
                String locadesc =MapUtils.getString(bySql.get(0),"locadesc");
                String proid =MapUtils.getString(bySql.get(0),"proid");
                String taskid =MapUtils.getString(bySql.get(0),"taskid");
                String purorder = MapUtils.getString(bySql.get(0), "purorder");
                String orgcode = MapUtils.getString(bySql.get(0), "orgcode");//单位
                String applicant = MapUtils.getString(bySql.get(0), "applicant");
                String subjectno = MapUtils.getString(bySql.get(0), "subjectno");//课题号
                String createuser = MapUtils.getString(bySql.get(0), "createuser");//创建人
                String deptcode = MapUtils.getString(bySql.get(0), "deptcode");//部门
                String applicantid = MapUtils.getString(bySql.get(0), "applicantid");//出库申请单申请人（领用人）
                String issueType = MapUtils.getString(bySql.get(0), "issueType");//出库类型
                String budgetitem = MapUtils.getString(bySql.get(0), "budgetitem");
//                List<Map<String, Object>> bySql1 = handlerService.findBySql("select invusenum from gq_invuse order by invusenum  desc limit 1");
//                String invusenum =MapUtils.getString(bySql1.get(0),"invusenum");
//                if(invusenum.equals("") || invusenum ==null){
//                    invusenum ="1001";
//                }else{
//                    Integer num =Integer.parseInt(invusenum);
//                    num++;
//                    invusenum=Integer.toString(num);
//                }
//               handlerService.updateBySql("insert into gq_invuse(invusenum,description,locations,locationsdesc,createtime,status,Istype) values('"+invusenum+"','"+description+"','"+location+"','"+locadesc+"',now(),'已审批','出库')");

                String itemapplynum =MapUtils.getString(bySql.get(0),"itemapplynum");
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_itemapplyline where glnum ='" + itemapplynum + "'");

                // 成本归集
                itemCostAccumulation(op.getVariables(), bySql2);
                List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                if (CollectionUtils.isNotEmpty(sys_setting)) {
                    String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                    if (field8.equals("1")) {
                        batreasuryqutbound(bySql2,description,location,locadesc,applicant,createuser,deptcode,applicantid,issueType,itemapplynum);
                    }else {
                        for (Map<String, Object> map : bySql2) {
                            String itemnum = MapUtils.getString(map, "itemnum");//物料编号
                            String locations = MapUtils.getString(map, "locations");//库房
                            String binnum = MapUtils.getString(map, "binnum");//货位
                            String orunit = MapUtils.getString(map, "Orunit");//订购单位
                            String curbal = MapUtils.getString(map, "curbal");
                            Float GRANTQTY = MapUtils.getFloat(map, "GRANTQTY");//出库数量
                            String wonum = MapUtils.getString(map, "wonum");
                            Float unitcost = MapUtils.getFloat(map, "unitcost");
                            String unitcost4 = MapUtils.getString(map, "unitcost");//单价
                            BigDecimal unitcost2 = new BigDecimal(unitcost4);
                            Float linecost = MapUtils.getFloat(map, "linecost");//金额
                            String lotnum = MapUtils.getString(map, "lotnum");//批次
                            Float quantity = MapUtils.getFloat(map, "quantity");//领料数量
                            String taskid1 = MapUtils.getString(map, "taskid");
                            String proid1 = MapUtils.getString(map, "proid");
                            String subjectno1 = MapUtils.getString(map, "subjectno");
                            String id2 = MapUtils.getString(map, "id");
                            Float outquantity = MapUtils.getFloat(map, "outquantity");
//                    List<Map<String, Object>> bySql11 = handlerService.findBySql("select t.* from gq_itemapplyline t left join gq_itemapply a on t.glnum=a.itemapplynum where t.itemnum='" + itemnum + "' and t.lotnum='" + lotnum + "'and a.status!='新建' and  a.status!='草稿' and a.status!='已核准'");
//                    if (CollectionUtils.isNotEmpty(bySql11)){
//                        Float grantqty5=(float) 0;
//                        for (int z=0;z<bySql11.size();z++){
//                            Map<String, Object> map1 = bySql11.get(z);
//                            Float grantqty = MapUtils.getFloat(map1, "GRANTQTY");
//                            grantqty5=grantqty5+grantqty;
//                        }
//                        List<Map<String, Object>> bySql10 = handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "' and batchnum='" + lotnum + "'");
//                        if (CollectionUtils.isNotEmpty(bySql10)){
//                            Map<String, Object> map1 = bySql10.get(0);
//                            Float avblbalance1 = MapUtils.getFloat(map1, "avblbalance");
//                            if (avblbalance1.compareTo(grantqty5)<0){
//                                throw new ServiceException("出库物料中存在库存不足的物料，请驳回到发起人，重新选择物料提交申请！");
//                            }
//                        }
//
                            handlerService.updateBySql("update gq_itemapplyline set reinvenantity=" + GRANTQTY + " where id='" + id2 + "'");
                            StringBuilder sbSql = new StringBuilder();
                            sbSql.append("select * from gq_invbalances where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");
                            if (StringUtils.isNotEmpty(proid1)) {
                                sbSql.append(" and proid= " + proid1);
                            } else if (StringUtils.isNotEmpty(subjectno1)) {
                                sbSql.append(" and subjectno= " + subjectno1);
                            } else if (StringUtils.isNotEmpty(taskid1)) {
                                sbSql.append(" and taskid = " + taskid1);
                            }

                            List<Map<String, Object>> bySql3 = handlerService.findBySql(sbSql.toString());
                            //库存余量curbal =curbal -quantity
                            Float curbalt = MapUtils.getFloat(bySql3.get(0), "curbal");
                            curbalt = curbalt - GRANTQTY;
                            //预留数量reservedqty =reservedqty +quantity
                            Float reservedqty = MapUtils.getFloat(bySql3.get(0), "reservedqty");
                            float f = 0;
                            if (reservedqty.compareTo(f) == 0) {
                                reservedqty = (float) 0;
                            } else {
                                reservedqty = reservedqty - GRANTQTY;
                            }
                            Float avblbalance = MapUtils.getFloat(bySql3.get(0), "avblbalance");
                            //可用数量 avblbalance =curbalt -reservedqty
                            avblbalance = avblbalance - GRANTQTY;
                            //待出库数量
                            outquantity = quantity - GRANTQTY;
                            handlerService.updateBySql("update gq_itemapplyline set outquantity=" + outquantity + " where id='" + id2 + "'");
                            if (taskid1 == null || taskid1 == "") {
                                handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + "  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");

                            } else {
                                handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + "  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");

                            }
                            List<Map<String, Object>> bySql5 = handlerService.findBySql("select avblbalance,curbal,reservedqty,numusage from gq_invbalances where itemnum  ='" + itemnum + "'and storenum ='" + location + "'");
                            float avblbalance2 = 0;
                            float curbal2 = 0;
                            float reservedqty2 = 0;
                            float numusage2=0;
                            if (CollectionUtils.isNotEmpty(bySql5)) {
                                for (int i = 0; i < bySql5.size(); i++) {
                                    Map<String, Object> map1 = bySql5.get(i);
                                    Float aFloat = MapUtils.getFloat(map1, "avblbalance");
                                    Float curbal1 = MapUtils.getFloat(map1, "curbal");
                                    Float reservedqty1 = MapUtils.getFloat(map1, "reservedqty");
                                    Float numusage = MapUtils.getFloat(map1, "numusage");
                                    avblbalance2 = avblbalance2 + aFloat;
                                    curbal2 = curbal2 + curbal1;
                                    reservedqty2 = reservedqty2 + reservedqty1;
                                    numusage2= numusage2+numusage;
                                }
                                handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal2 + ", avblbalance = " + avblbalance2 + ",reservedqty=" + reservedqty2 + ",numusage="+numusage2+" where storenum = '" + location + "' and itemnum = '" + itemnum + "'");

                            }
                            String outonumNew = "";//出库编号
                            List<Map<String, Object>> bySql9 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFO%' order by instonum desc limit 1");
                            if (CollectionUtils.isNotEmpty(bySql9)) {
                                Map<String, Object> map1 = bySql9.get(0);
                                String instonum = MapUtils.getString(map1, "instonum");
                                int integer = Integer.valueOf(instonum.substring(instonum.length() - 8));
                                integer++;
                                outonumNew = "CDFO" + integer;
                            } else {
                                outonumNew = "CDFO10000001";
                            }
                            //添加到 出库单记录表
                            //写入内容包含：物料编号、物料描述、交易类型（出库）、数量、单位、交易时间（创建时间）、交易处理人（创建人）
                            List<Map<String, Object>> bySql4 = handlerService.findBySql("select itemdesc,outunit from gq_inventory where itemnum ='" + itemnum + "'");
                            String itemdesc = MapUtils.getString(bySql4.get(0), "itemdesc");
                            String outunit = MapUtils.getString(bySql4.get(0), "outunit");
                            LoginAppUser user = SysUserUtil.getLoginAppUser();
                            Long id1 = user.getId();
                            String createuserdesc = user.getNickname();
                            handlerService.updateBySql("insert into gq_matusetrans (subjectno,deptcode,instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,createuserdesc,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid,sublessordesc,binnum,receiptnum) values('" + subjectno1 + "','" + deptcode + "','" + outonumNew + "','" + description + "','" + itemnum + "','" + itemdesc + "'," + GRANTQTY + ",'" + orunit + "',now(),'" + createuser + "','" + createuserdesc + "','" + location + "','" + locadesc + "','" + lotnum + "','" + issueType + "'," + unitcost2 + "," + linecost + ",'" + proid1 + "','" + taskid1 + "','" + applicant + "','" + binnum + "','" + itemapplynum + "')");
//                    List<Map<String, Object>> bySql6 = handlerService.findBySql("select avblbalance,version from gq_invbalances where itemnum='" + itemnum + "'and storenum ='" + location + "' and batchnum='" + lotnum + "' ");
//                    if (CollectionUtils.isNotEmpty(bySql6)){
//                        Map<String, Object> map2 = bySql6.get(0);
//                        Float avblbalance1 = MapUtils.getFloat(map2, "avblbalance");
//                        Integer version = MapUtils.getInteger(map2, "version");
//                        version=version+1;
//                       // handlerService.updateBySql("update gq_itemapplyline set avblbalance ="+avblbalance1+" where itemnum='" + itemnum + "' and lotnum='" + lotnum + "'");
//                        handlerService.updateBySql("update gq_invbalances set version="+version+" where itemnum='" + itemnum + "'and storenum ='" + location + "' and batchnum='" + lotnum + "'");
//                    }
                            /**
                             * 1.获取sys_setting 里设置的门槛金额
                             * 2.判断出库清单物料价格和贵重物料门槛比对
                             * 3.高于这个门槛的往物料消耗单放数据
                             */
                            //1.获取sys_setting 里设置的门槛金额
                            List<Map<String, Object>> field1List = handlerService.findBySql("select field1 from sys_setting");
                            if (CollectionUtils.isNotEmpty(field1List)) {
                                Map<String, Object> map1 = field1List.get(0);
                                Float field1 = MapUtils.getFloat(map1, "field1");
                                if (unitcost.compareTo(field1) > 0) {
                                    for (int i = 0; i < GRANTQTY; i++) {
                                        //2.判断出库清单物料价格和贵重物料门槛比对
                                        Map<String, Object> materialuseMap = new HashMap<>();
//                            Map<String, Object> materialuselistMap = new HashMap<>();
                                        List<Map<String, Object>> materialusenumList = handlerService.findBySql("select materialusenum from gq_materialusenew ORDER by materialusenum desc");
                                        String materialusenum = "1001";
                                        if (CollectionUtils.isNotEmpty(materialusenumList)) {
                                            Map<String, Object> map2 = materialusenumList.get(0);
                                            String materialusenum1 = MapUtils.getString(map2, "materialusenum");
                                            materialusenum = String.valueOf(Integer.parseInt(materialusenum1) + 1);
                                            materialuseMap.put("materialusenum", materialusenum);
                                        } else {
                                            materialuseMap.put("materialusenum", materialusenum);
                                        }
                                        materialuseMap.put("outboundorderid", id);//出库申请单id
                                        materialuseMap.put("description", description);//描述
                                        materialuseMap.put("status", "新建");//状态
                                        materialuseMap.put("itemnum", itemnum);//物料编号
                                        materialuseMap.put("itemEnity_description", itemdesc);//物料描述
                                        materialuseMap.put("company", orunit);//订购单位
                                        //为了解决出库数量为小数问题。剩余0.5 生成一条贵重物料单据数量为0.5
                                        float v = GRANTQTY - i;
                                        if (v < 1f) {
                                            materialuseMap.put("outquantity", v);//出库数量
                                        } else {
                                            materialuseMap.put("outquantity", 1);//出库数量
                                        }

                                        String unitcost1 = MapUtils.getString(map, "unitcost");
                                        materialuseMap.put("unitcost", unitcost1);//单价
                                        materialuseMap.put("lotnum", lotnum);//批次
                                        materialuseMap.put("relationnumnew", "0");//关联父编号new
                                        materialuseMap.put("materialgoing", "未使用");//物料去向为未使用
//                            materialuseMap.put("location",location);//库房编号
//                            materialuseMap.put("locadesc",locadesc);//库房描述
//                            List<Map<String, Object>> bySql1 = handlerService.findBySql("select proname,pronum from gq_proaccount where id =" + proid);
//                            if(CollectionUtils.isNotEmpty(bySql1)){
//                                Map<String, Object> map2 = bySql1.get(0);
//                                materialuseMap.put("projectEntity_proname",MapUtils.getString(map2,"proname"));//项目名称
//                                materialuseMap.put("projectEntity_pronum",MapUtils.getString(map2,"pronum"));//项目编号
//                                materialuseMap.put("proid",proid);//项目id
//                            }
//                            List<Map<String, Object>> bySql6 = handlerService.findBySql("select name,tasknum from gq_scheduleplantask where id =" + taskid);
//                            if(CollectionUtils.isNotEmpty(bySql6)){
//                                Map<String, Object> map2 = bySql6.get(0);
//                                materialuseMap.put("taskid",MapUtils.getString(map2,"tasknum"));//任务编号
//                                materialuseMap.put("taskEntity_name",MapUtils.getString(map2,"name"));//任务名称
//                            }
                                        //创建人创建时间
                                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select id,deptcode,nickname from sys_user where field10 = '" + applicantid + "'");
                                        if (CollectionUtils.isNotEmpty(bySql1)) {
                                            materialuseMap.put("updateuser", MapUtils.getString(bySql1.get(0), "id"));//修改人
                                            materialuseMap.put("createuser", MapUtils.getString(bySql1.get(0), "id"));//创建人
                                            materialuseMap.put("createuserdesc", MapUtils.getString(bySql1.get(0), "nickname"));//创建人描述
                                            materialuseMap.put("updatetime", new Date());//修改时间
                                            materialuseMap.put("createtime", new Date());//创建时间
                                            List<Map<String, Object>> bySql7 = handlerService.findBySql("select dept.fullname as perdeptfullname from gq_person per left join sys_dept dept on dept.code = per.deptcode " +
                                                    " where per.personid = (select usr.field2 from sys_user usr where usr.id = " + MapUtils.getString(bySql1.get(0), "id") + ")");
                                            if (CollectionUtils.isNotEmpty(bySql7)) {
                                                Map<String, Object> map2 = bySql7.get(0);
                                                materialuseMap.put("deptcodeEnity_fullname", MapUtils.getString(map2, "perdeptfullname"));
                                            }
                                        }

                                        List<Map<String, Object>> bySql8 = handlerService.findBySql("select fullname from sys_dept where code = '" + MapUtils.getString(bySql1.get(0), "deptcode") + "'");
                                        if (CollectionUtils.isNotEmpty(bySql8)) {
                                            Map<String, Object> map2 = bySql8.get(0);
                                            materialuseMap.put("orgcodeEnity_fullname", MapUtils.getString(map2, "fullname"));
                                        }

//                            materialuselistMap.put("maternum",materialusenum);//关联主表编号
//                            materialuselistMap.put("itemnum",itemnum);//物料编号
//                            materialuselistMap.put("itemEnity_description",itemdesc);//物料描述
//                            materialuselistMap.put("company",orunit);//订购单位
//                            materialuselistMap.put("outquantity",GRANTQTY);//出库数量
//                            materialuselistMap.put("unitcost",unitcost);//单价
//                            materialuselistMap.put("lotnum",lotnum);//批次
//                            materialuselistMap.put("locations",locations);//库房编号
//                            //创建人创建时间
//                            materialuselistMap.put("updateuser",id1);//修改人
//                            materialuselistMap.put("createuser",id1);//创建人
//                            materialuselistMap.put("updatetime",new Date());//修改时间
//                            materialuselistMap.put("createtime",new Date());//创建时间

                                        handlerService.insert("gq_materialusenew", materialuseMap);//往物料消耗主表
//                            handlerService.insert("gq_materialuselistnew",materialuselistMap);//往物料消耗子表
                                        handlerService.findBySql("update gq_materialusenew set createuser = '" + MapUtils.getString(bySql1.get(0), "id") + "' where materialusenum = '" + materialusenum + "'");
                                    }
                                    //修改领料申请子表物料的是否为贵重物料为贵重String itemnum =MapUtils.getString(map,"itemnum");
                                    String id3 = MapUtils.getString(map, "id");//领料申请子表id
                                    handlerService.findBySql("update gq_itemapplyline set isvaluable = '贵重' where id = '" + id3 + "'");
                                }
                            }
                        }
                    }
                }
            }
        }else if (flowNode.getId().equals("xmfzr1") && op.isFlag()||flowNode.getId().equals("zhglbld") && op.isFlag()||flowNode.getId().equals("kfbld") && op.isFlag()||flowNode.getId().equals("bmld3") && op.isFlag()){
            //库管员审批之前的节点审批完成后给waitingtime字段存放当前时间  用于库管员未领料预警
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(new Date());
            handlerService.findBySql("update gq_itemapply set waitingtime = '" + format + "' where id ='" + id + "'");
        }
        super.afterExcuteFlow(app, id, flowNode, op, event);
    }

    private void batreasuryqutbound(List<Map<String, Object>> bySql2,String description,String location,String locadesc,String applicant,String createuser,String deptcode,String applicantid,String issueType,String itemapplynum) throws Exception {
        for (Map<String, Object> map : bySql2) {
            String itemnum = MapUtils.getString(map, "itemnum");//物料编号
            String locations = MapUtils.getString(map, "locations");//库房
            String binnum = MapUtils.getString(map, "binnum");//货位
            String orunit = MapUtils.getString(map, "Orunit");//订购单位
            String curbal = MapUtils.getString(map, "curbal");
            Float GRANTQTY = MapUtils.getFloat(map, "GRANTQTY");//出库数量
            String wonum = MapUtils.getString(map, "wonum");
            Float unitcost = MapUtils.getFloat(map, "unitcost");
            String unitcost4 = MapUtils.getString(map, "unitcost");//单价
            BigDecimal unitcost2 = new BigDecimal(unitcost4);
            Float linecost = MapUtils.getFloat(map, "linecost");//金额
            String lotnum = MapUtils.getString(map, "lotnum");//批次
            Float quantity = MapUtils.getFloat(map, "quantity");//领料数量
            String taskid1 = MapUtils.getString(map, "taskid");
            String proid1 = MapUtils.getString(map, "proid");
            String subjectno1 = MapUtils.getString(map, "subjectno");
            String id2 = MapUtils.getString(map, "id");
            Float outquantity = MapUtils.getFloat(map, "outquantity");
            handlerService.updateBySql("update gq_itemapplyline set reinvenantity=" + GRANTQTY + " where id='" + id2 + "'");
            StringBuilder sbSql = new StringBuilder();
            sbSql.append("select * from gq_invbalances where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");
            if (StringUtils.isNotEmpty(proid1)) {
                sbSql.append(" and proid= " + proid1);
            } else if (StringUtils.isNotEmpty(subjectno1)) {
                sbSql.append(" and subjectno= " + subjectno1);
            } else if (StringUtils.isNotEmpty(taskid1)) {
                sbSql.append(" and taskid = " + taskid1);
            }
            List<Map<String, Object>> bySql3 = handlerService.findBySql(sbSql.toString());
            if (CollectionUtils.isNotEmpty(bySql3)){
                String id = MapUtils.getString(bySql3.get(0), "id");
                List<Map<String,String>> maps= new ArrayList<>();

                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_occurecords where invbalancesid='" + id + "' and applyby='"+applicantid+"'");
                if (CollectionUtils.isNotEmpty(bySql)){
                    Float numusage =(float) 0;
                    Float numusage2 =(float) 0;
                    for (int i=0;i<bySql.size();i++){
                        Map<String, Object> map1 = bySql.get(i);

                        //6262: 9.0, 6224: 10.0, 6224: 4.0,
//                    String[] keyValuePairs = occurecords.split(", ");//将拼接后的字符串以适当的分隔符进行拆分
//                    for (String keyValuePair : keyValuePairs) {
//                        HashMap<String, String> hashMap = new HashMap<>();
//                        String[] keyValue = keyValuePair.split(": ");
//                        String key = keyValue[0];
//                        String value = keyValue[1];
//                        String cleanedStr = value.replace(",", "");
//                        Float numusage1 = Float.valueOf(cleanedStr);
//                        if (key.equals(applicantid)){
//                            numusage=numusage+numusage1;//占用量
//                        }else {
//                            numusage2=numusage2+numusage1;
//                            hashMap.put(key, cleanedStr);
//                            maps.add(hashMap);
//                        }
//                    }
                        Float numusage1 = MapUtils.getFloat(map1, "numusage");
                        numusage=numusage+numusage1;
                        handlerService.updateBySql("DELETE FROM gq_occurecords WHERE invbalancesid='" + id + "' and applyby='"+applicantid+"'");
                    }

                        Float curbalt = MapUtils.getFloat(bySql3.get(0), "curbal");
                        curbalt = curbalt - GRANTQTY;
                        Float avblbalance = MapUtils.getFloat(bySql3.get(0), "avblbalance");
                        //占用量大于出库数量
                        if (numusage.compareTo(GRANTQTY)>0){
                            numusage=numusage-GRANTQTY;
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("numusage",numusage);
                            hashMap.put("applyby",applicantid);
                            hashMap.put("invbalancesid",id);
                            handlerService.insert("gq_occurecords",hashMap);
                        }else {
                            //占用量小于出库数量
                            GRANTQTY=GRANTQTY-numusage;
                            numusage=(float)0;
                            avblbalance = avblbalance - GRANTQTY;
                        }
//                        HashMap<String, String> hashMap1 = new HashMap<>();
//                        if (numusage.compareTo((float)0)>0){
//                            String floatString1 = String.valueOf(numusage);
//                            hashMap1.put(applicantid, floatString1);
//                            maps.add(hashMap1);
//                        }
//                        StringBuilder stringBuilder = new StringBuilder();
//                        for (Map<String, String> hashMapList : maps) {
//                            for (Map.Entry<String, String> entry : hashMapList.entrySet()) {
//                                String key = entry.getKey();
//                                Object value = entry.getValue();
//                                stringBuilder.append(key).append(": ").append(value).append(", ");
//                            }
//                        }
//                        String occurecordss = stringBuilder.toString();

                        //预留数量reservedqty =reservedqty +quantity
                        Float reservedqty = MapUtils.getFloat(bySql3.get(0), "reservedqty");
                        float f = 0;
                        if (reservedqty.compareTo(f) == 0) {
                            reservedqty = (float) 0;
                        } else {
                            reservedqty = reservedqty - GRANTQTY;
                        }
                        //可用数量 avblbalance =curbalt -reservedqty
                        outquantity = quantity - GRANTQTY;
                        numusage2=numusage2+numusage;
                        handlerService.updateBySql("update gq_itemapplyline set outquantity=" + outquantity + " where id='" + id2 + "'");
                        if (taskid1 == null || taskid1 == "") {
                            handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + ",numusage="+numusage2+"  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");

                        } else {
                            handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + ",numusage=" + numusage2 + "  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");


                        }
                }else{
                    Float curbalt = MapUtils.getFloat(bySql3.get(0), "curbal");
                    curbalt = curbalt - GRANTQTY;
                    //预留数量reservedqty =reservedqty +quantity
                    Float reservedqty = MapUtils.getFloat(bySql3.get(0), "reservedqty");
                    float f = 0;
                    if (reservedqty.compareTo(f) == 0) {
                        reservedqty = (float) 0;
                    } else {
                        reservedqty = reservedqty - GRANTQTY;
                    }
                    Float avblbalance = MapUtils.getFloat(bySql3.get(0), "avblbalance");
                    //可用数量 avblbalance =curbalt -reservedqty
                    avblbalance = avblbalance - GRANTQTY;
                    //待出库数量
                    outquantity = quantity - GRANTQTY;
                    handlerService.updateBySql("update gq_itemapplyline set outquantity=" + outquantity + " where id='" + id2 + "'");
                    if (taskid1 == null || taskid1 == "") {
                        handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + "  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");

                    } else {
                        handlerService.updateBySql("update gq_invbalances set curbal =" + curbalt + ",reservedqty=" + reservedqty + ",avblbalance=" + avblbalance + "  where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='" + lotnum + "' and binnum='" + binnum + "'");

                    }

                }
                List<Map<String, Object>> bySql5 = handlerService.findBySql("select avblbalance,curbal,reservedqty,numusage from gq_invbalances where itemnum  ='" + itemnum + "'and storenum ='" + location + "'");
                float avblbalance2 = 0;
                float curbal2 = 0;
                float reservedqty2 = 0;
                float numusage2=0;
                if (CollectionUtils.isNotEmpty(bySql5)) {
                    for (int i = 0; i < bySql5.size(); i++) {
                        Map<String, Object> map1 = bySql5.get(i);
                        Float aFloat = MapUtils.getFloat(map1, "avblbalance");
                        Float curbal1 = MapUtils.getFloat(map1, "curbal");
                        Float reservedqty1 = MapUtils.getFloat(map1, "reservedqty");
                        Float numusage = MapUtils.getFloat(map1, "numusage");
                        avblbalance2 = avblbalance2 + aFloat;
                        curbal2 = curbal2 + curbal1;
                        reservedqty2 = reservedqty2 + reservedqty1;
                        numusage2=numusage2+numusage;
                    }
                    handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal2 + ", avblbalance = " + avblbalance2 + ",reservedqty=" + reservedqty2 + ",numusage="+numusage2+" where storenum = '" + location + "' and itemnum = '" + itemnum + "'");

                }
                String outonumNew = "";//出库编号
                List<Map<String, Object>> bySql9 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFO%' order by instonum desc limit 1");
                if (CollectionUtils.isNotEmpty(bySql9)) {
                    Map<String, Object> map1 = bySql9.get(0);
                    String instonum = MapUtils.getString(map1, "instonum");
                    int integer = Integer.valueOf(instonum.substring(instonum.length() - 8));
                    integer++;
                    outonumNew = "CDFO" + integer;
                } else {
                    outonumNew = "CDFO10000001";
                }
                //添加到 出库单记录表
                //写入内容包含：物料编号、物料描述、交易类型（出库）、数量、单位、交易时间（创建时间）、交易处理人（创建人）
                List<Map<String, Object>> bySql4 = handlerService.findBySql("select itemdesc,outunit from gq_inventory where itemnum ='" + itemnum + "'");
                String itemdesc = MapUtils.getString(bySql4.get(0), "itemdesc");
                String outunit = MapUtils.getString(bySql4.get(0), "outunit");
                LoginAppUser user = SysUserUtil.getLoginAppUser();
                Long id1 = user.getId();
                String createuserdesc = user.getNickname();
                handlerService.updateBySql("insert into gq_matusetrans (subjectno,deptcode,instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,createuserdesc,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid,sublessordesc,binnum,receiptnum) values('" + subjectno1 + "','" + deptcode + "','" + outonumNew + "','" + description + "','" + itemnum + "','" + itemdesc + "'," + GRANTQTY + ",'" + orunit + "',now(),'" + createuser + "','" + createuserdesc + "','" + location + "','" + locadesc + "','" + lotnum + "','" + issueType + "'," + unitcost2 + "," + linecost + ",'" + proid1 + "','" + taskid1 + "','" + applicant + "','" + binnum + "','" + itemapplynum + "')");
            }
        }
    }
    /**
     * 成本归集
     *
     * @param headMap
     * @param lineList
     */
    private void itemCostAccumulation(Map<String, Object> headMap, List<Map<String, Object>> lineList) throws Exception {
        CostAttribute costAttribute = new CostAttribute();
        costAttribute.setName(MapUtils.getString(headMap, "description"));// 业务申请名称
        costAttribute.setProId(MapUtils.getInteger(headMap, "proid"));// 项目id
        costAttribute.setSubjectNo(MapUtils.getString(headMap, "subjectno"));// 课题号
        costAttribute.setTaskid(MapUtils.getInteger(headMap, "taskid"));// 任务id
        costAttribute.setCostItemId(MapUtils.getInteger(headMap, "pbid"));
        costAttribute.setCostSource("个人领用");

        Double totalCost = 0d;
        List<CostDetailAttribute> costDetailAttributes = new ArrayList<CostDetailAttribute>();
        // 组织名称物料信息
        for (Map<String, Object> lineMap : lineList) {
            Double lineCost = MapUtils.getDouble(lineMap, "linecost");
            Double quantity = MapUtils.getDouble(lineMap, "quantity");
            float unitcost = MapUtils.getFloat(lineMap, "unitcost");
            Integer itemId = MapUtils.getInteger(lineMap, "itemid");
            String itemDesc = MapUtils.getString(lineMap, "itemdesc");

            totalCost = totalCost + lineCost;

            CostDetailAttribute costDetailAttribute = new CostDetailAttribute();
            costDetailAttribute.setItemId(itemId);
            costDetailAttribute.setName(itemDesc);
            costDetailAttribute.setUnitPrice(BigDecimal.valueOf(unitcost));
            costDetailAttribute.setQuantity(BigDecimal.valueOf(quantity));
            costDetailAttribute.setTotalprice(BigDecimal.valueOf(lineCost));

            costDetailAttributes.add(costDetailAttribute);
        }

        costAttribute.setTotalCost(BigDecimal.valueOf(totalCost));// 总计金额
        costAttribute.setOrderId(MapUtils.getInteger(headMap, "id").toString());// 关联合同/出入库等单据id
        costAttribute.setOrderNo(MapUtils.getString(headMap, "itemapplynum"));// 关联合同/出入库等单据编号
        costAttribute.setCostDetailAttributes(costDetailAttributes);

        costAccumulationService.itemCostAccumulation(costAttribute);
    }

//    @Override
//    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
//        if ("itemapplyApp".equals(app)){
//            if ("gq_itemapplyline".equals(objName)){
//                String id = MapUtils.getString(data, "id");
//                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_itemapplyline where id=" + id);
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        Float quantity = MapUtils.getFloat(map, "quantity");
//                        Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
//                        if (quantity>grantqty){
//                            return "领用物料未完全出库，请更改出库数量";
//                        }
//                    }
//                }
//            }
//        }
//        return super.validateSave(app, objName, data);
//    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("itemapplyApp".equals(app)) {
            if (isUpdate==true){
                    log.info("+++++++++++++++++++++++++++++++++++++++++="+data);
                    String glnum = MapUtils.getString(data, "glnum");

                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_itemapply where itemapplynum='" + glnum + "'");//查询主表
                    if (CollectionUtils.isNotEmpty(bySql)){
                        String status = MapUtils.getString(bySql.get(0), "status");
                        String itemapplynum = MapUtils.getString(bySql.get(0), "itemapplynum");
                        String description = MapUtils.getString(bySql.get(0), "description");
                        String locadesc = MapUtils.getString(bySql.get(0), "locadesc");
                        String subjectno = MapUtils.getString(bySql.get(0), "subjectno");
                        String taskid = MapUtils.getString(bySql.get(0), "taskid");
                        String proid = MapUtils.getString(bySql.get(0), "proid");
                        String location = MapUtils.getString(bySql.get(0), "location");
                        List<Map<String, Object>> bySql6 = handlerService.findBySql("select subjectno from gq_itemapplyline where glnum ='" + glnum + "'");
//                        if (CollectionUtils.isNotEmpty(bySql6)){
//                            Map<String, Object> map = bySql6.get(0);
//                            String subjectno1 = MapUtils.getString(map, "subjectno");
//                            String subjectno2 = MapUtils.getString(data, "subjectno");
//                            if (subjectno1.equals(subjectno2)){
//
//                            }else {
//                                throw  new ServiceException("请选择课题号为'"+subjectno1+"'的物料") ;
//                            }
//                        }
//                        if (status.equals("已核准")){
//                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_itemapplyline where glnum ='" + glnum + "'");
//                            if (CollectionUtils.isNotEmpty(bySql2)){
//                                for(Map<String,Object> map :bySql2){
//                                    String itemnum =MapUtils.getString(map,"itemnum");
//                                    String locations = MapUtils.getString(map, "locations");
//                                    String binnum = MapUtils.getString(map, "binnum");
//                                    String curbal =MapUtils.getString(map,"curbal");
//                                    Float GRANTQTY =MapUtils.getFloat(map,"GRANTQTY");
//                                    String wonum =MapUtils.getString(map,"wonum");
//                                    Float unitcost = MapUtils.getFloat(map, "unitcost");
//                                    Float linecost =MapUtils.getFloat(map,"linecost");
//                                    String lotnum =MapUtils.getString(map,"lotnum");
//                                    Float quantity = MapUtils.getFloat(map, "quantity");
//                                    String taskid1 = MapUtils.getString(map, "taskid");
//                                    String proid1 = MapUtils.getString(map, "proid");
//                                    String subjectno1 = MapUtils.getString(bySql.get(0), "subjectno");
//                                    String id2 = MapUtils.getString(map, "id");
//                                    Float outquantity =MapUtils.getFloat(map, "outquantity");
//                                    Float grantqty = MapUtils.getFloat(data, "GRANTQTY");
//                                    if (grantqty.equals(GRANTQTY)){
//
//                                    }else {
//                                        List<Map<String, Object>> bySql3=null;
//                                        if (taskid==null||taskid==""){
//                                             bySql3 = handlerService.findBySql("select * from gq_invbalances where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"' and binnum='"+binnum+"'and proid='"+proid+"'and subjectno='"+subjectno1+"'");
//
//                                        }else {
//                                            bySql3 = handlerService.findBySql("select * from gq_invbalances where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"' and binnum='"+binnum+"'and taskid='"+taskid+"'and proid='"+proid+"'and subjectno='"+subjectno1+"'");
//
//                                        }
//                                        //库存余量curbal =curbal -quantity
//                                        Float curbalt = MapUtils.getFloat(bySql3.get(0),"curbal");
//                                        curbalt=curbalt - grantqty;
////                                        //预留数量reservedqty =reservedqty +quantity
//                                        Float reservedqty = MapUtils.getFloat(bySql3.get(0),"reservedqty");
//                                        float f =0;
//                                        if (reservedqty.compareTo(f)==0){
//                                           reservedqty=(float)0;
//                                        }else {
//                                            reservedqty=reservedqty -grantqty;
//                                        }
//                                        //可用数量 avblbalance =curbalt -reservedqty
//                                        Float avblbalance =curbalt -grantqty;
//                                        if (avblbalance>=0){
//                                            if (taskid1==null||taskid1==""){
//                                                handlerService.updateBySql("update gq_invbalances set curbal ="+curbalt+",avblbalance="+avblbalance+"  where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"'and binnum='"+binnum+"'and proid='"+proid1+"'and subjectno='"+subjectno1+"'");
//
//                                            }else {
//                                                handlerService.updateBySql("update gq_invbalances set curbal ="+curbalt+",avblbalance="+avblbalance+"  where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"'and binnum='"+binnum+"'and taskid='"+taskid1+"'and proid='"+proid1+"'and subjectno='"+subjectno1+"'");
//
//                                            }
//                                        }else {
//                                            avblbalance=(float)0;
//                                            if (taskid==null||taskid==""){
//                                                handlerService.updateBySql("update gq_invbalances set curbal ="+curbalt+",avblbalance="+avblbalance+"  where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"'and binnum='"+binnum+"'and proid='"+proid1+"'and subjectno='"+subjectno1+"'");
//
//                                            }else {
//                                                handlerService.updateBySql("update gq_invbalances set curbal ="+curbalt+",avblbalance="+avblbalance+"  where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"'and binnum='"+binnum+"'and taskid='"+taskid1+"'and proid='"+proid1+"'and subjectno='"+subjectno1+"'");
//
//                                            }
//                                        }
//                                        //调整预留数量
//                                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select avblbalance,curbal,reservedqty,batchnum,binnum,proid,subjectno from gq_invbalances where itemnum  ='" + itemnum + "'and storenum ='" + locations + "'");
//                                            if (CollectionUtils.isNotEmpty(bySql1)){
//                                                for (int j=0;j<bySql1.size();j++){
//                                                    Map<String, Object> map1 = bySql1.get(j);
//                                                    Float curbal1 = MapUtils.getFloat(map1, "curbal");
//                                                    String batchnum = MapUtils.getString(map1, "batchnum");
//                                                    String binnum1 = MapUtils.getString(map1, "binnum");
//                                                    String proid2 = MapUtils.getString(map1, "proid");
//                                                    String subjectno2 = MapUtils.getString(map1, "subjectno");
//                                                    if (curbal1==0){
//                                                        handlerService.updateBySql("update gq_invbalances set reservedqty=0 where storenum ='" + locations + "' and itemnum ='" + itemnum + "' and batchnum ='"+lotnum+"'and binnum='"+binnum+"'and proid='"+proid2+"'and subjectno='"+subjectno2+"' ");
//                                                    }
//                                                }
//                                            }
//                                        List<Map<String, Object>> bySql5 = handlerService.findBySql("select avblbalance,curbal,reservedqty from gq_invbalances where itemnum  ='" + itemnum + "'and storenum ='" + locations + "'");
//                                        float avblbalance2 =0;
//                                        float curbal2 =0;
//                                        float reservedqty2 =0;
//                                        if (CollectionUtils.isNotEmpty(bySql5)){
//                                            for (int i=0;i<bySql5.size();i++){
//                                                Map<String, Object> map1 = bySql5.get(i);
//                                                Float aFloat = MapUtils.getFloat(map1,"avblbalance");
//                                                Float curbal1 = MapUtils.getFloat(map1, "curbal");
//                                                Float reservedqty1 = MapUtils.getFloat(map1, "reservedqty");
//                                                avblbalance2=avblbalance2+aFloat;
//                                                curbal2=curbal2+curbal1;
//                                                reservedqty2=reservedqty2+reservedqty1;
//                                            }
//                                            handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal2 + ", avblbalance = " + avblbalance2 +  ",reservedqty="+reservedqty2+" where storenum = '" + locations + "' and itemnum = '" + itemnum + "'");
//
//                                        }
//
//
//                                        List<Map<String, Object>> bySql4 = handlerService.findBySql("select itemdesc,outunit from gq_inventory where itemnum ='" + itemnum + "'");
//                                        String itemdesc =MapUtils.getString(bySql4.get(0),"itemdesc");
//                                        String outunit =MapUtils.getString(bySql4.get(0),"outunit");
//                                        LoginAppUser user = SysUserUtil.getLoginAppUser();
//                                        Long id1= user.getId();
//                                        String createuserdesc = user.getNickname();
//                                        float linecost1=grantqty*unitcost;
//                                        handlerService.updateBySql("insert into gq_matusetrans (instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,createuserdesc,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid) values('"+itemapplynum+"','"+description+"','"+itemnum+"','"+itemdesc+"',"+grantqty+",'"+outunit+"',now(),"+id1+",'"+createuserdesc+"','"+locations+"','"+locadesc+"','"+lotnum+"','出库',"+unitcost+","+linecost1+",'"+proid1+"','"+taskid1+"')");
//                                        handlerService.updateBySql("insert into gq_matusetrans (instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,createuserdesc,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid) values('"+itemapplynum+"','"+description+"','"+itemnum+"','"+itemdesc+"',"+grantqty+",'"+outunit+"',now(),"+id1+",'"+createuserdesc+"','"+locations+"','"+locadesc+"','"+lotnum+"','出库',"+unitcost+","+linecost1+",'"+proid1+"','"+taskid1+"')");
//                                    }
//                                }
//                            }
//                        }
//                        else {
//                            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_itemapplyline where glnum='" + itemapplynum + "'");
//                            if (CollectionUtils.isNotEmpty(bySql1)){
//                                for (int i=0;i<bySql1.size();i++){
//                                    Map<String, Object> map = bySql1.get(i);
//                                    String itemnum = MapUtils.getString(map, "itemnum");
//                                    String lotnum = MapUtils.getString(map, "lotnum");
//                                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select version from gq_invbalances where itemnum='" + itemnum + "' and storenum='" + location + "' and batchnum='" + lotnum + "'");
//                                    if (CollectionUtils.isNotEmpty(bySql2)){
//                                        Map<String, Object> map2 = bySql2.get(0);
//                                        String version = MapUtils.getString(map2, "version");
//                                        String versions = MapUtils.getString(data, "versions");
//                                        if (!version.equals(versions)){
//                                            throw new ServiceException("库存可用数量已发生改变请重新选择物料！");
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                        String id = MapUtils.getString(data, "id");
//                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_itemapplyline where id=" + id);
//                        if (CollectionUtils.isNotEmpty(bySql1)){
//                            for (int i=0;i<bySql1.size();i++){
//                                Map<String, Object> map = bySql1.get(i);
//                                Float quantity = MapUtils.getFloat(map, "quantity");
//                                Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
//                                if (quantity>grantqty){
//                                    throw new ServiceException("领用物料未完全出库，请更改出库数量") ;
//                                }
//                            }
//                        }
                    }
                }

                }
//            else if (isUpdate==false){
//                String id = MapUtils.getString(data, "id");
//                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_itemapplyline where id=" + id);
//                if (CollectionUtils.isNotEmpty(bySql1)){
//                    for (int i=0;i<bySql1.size();i++){
//                        Map<String, Object> map = bySql1.get(i);
//                        Float quantity = MapUtils.getFloat(map, "quantity");
//                        Float grantqty = MapUtils.getFloat(map, "GRANTQTY");
//                        if (quantity>grantqty){
//                            throw new ServiceException("领用物料未完全出库，请更改出库数量") ;
//                        }
//                    }
//                }
//            }



            super.beforSave(app, objName, data, isUpdate);
        }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("itemapplyApp".equals(app)){
            if ("gq_itemapplyline".equals(objName)){
                //根据主表课题号和子表课题号决定是否为计划外领用   collectout=1为计划外领用 collectout=0不是计划外领用
                if (isUpdate==true){
                    String id = MapUtils.getString(data, "id");
                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_itemapplyline where id=" + id);
                    if (CollectionUtils.isNotEmpty(bySql)){
                        Map<String, Object> map = bySql.get(0);
                        String subjectno = MapUtils.getString(map, "subjectno");
                        String glnum = MapUtils.getString(map, "glnum");
                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select subjectno from gq_itemapply where itemapplynum ='" + glnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql1)){
                            Map<String, Object> map1 = bySql1.get(0);
                            String subjectno1 = MapUtils.getString(map1, "subjectno");
                            if(!subjectno.equals(subjectno1)){
                                handlerService.updateBySql("update gq_itemapply set collectout =1 where itemapplynum='"+glnum+"'");
                            }else {
                                handlerService.updateBySql("update gq_itemapply set collectout =0 where itemapplynum='"+glnum+"'");
                            }
                        }
                    }
                }else {
                    String id = MapUtils.getString(data, "id");
                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_itemapplyline where id=" + id);
                    if (CollectionUtils.isNotEmpty(bySql)){
                        Map<String, Object> map = bySql.get(0);
                        String subjectno = MapUtils.getString(map, "subjectno");
                        String glnum = MapUtils.getString(map, "glnum");
                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select subjectno from gq_itemapply where itemapplynum ='" + glnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql1)){
                            Map<String, Object> map1 = bySql1.get(0);
                            String subjectno1 = MapUtils.getString(map1, "subjectno");
                            if(!subjectno.equals(subjectno1)){
                                handlerService.updateBySql("update gq_itemapply set collectout =1 where itemapplynum='"+glnum+"'");
                            }else {
                                handlerService.updateBySql("update gq_itemapply set collectout =0 where itemapplynum='"+glnum+"'");
                            }
                        }
                    }
                }

            }else if ("gq_itemapply".equals(objName)){
                //处理数据变更流程标识（决定领用流程走向）
                processingData(data);
            }
        }
        super.afterSave(app, objName, data, isUpdate);
    }

    private void processingData(Map<String, Object> data) {
        String id = MapUtils.getString(data, "id");//出库单id
        String itemapplynum = "";//出库编码
        String iscenterstore = "";//流程标识（是否为中心库房）
        String issonpricemany = "1";//流程标识（子表单价是否有超过1万）
        String issonsubject = "";//流程标识（子表课题号是否为科研课题号）


        //流程标识（是否为中心库房）1：不是中心库房2：是中心库房
        List<Map<String, Object>> bySql = handlerService.findBySql("SELECT a.itemapplynum,IF(b.waregrade='中心库房','2','1') as iscenterstore from gq_itemapply a LEFT JOIN gq_store b on a.location=b.storenum where a.id = '" + id + "'");
        if(CollectionUtils.isNotEmpty(bySql)){
            iscenterstore = MapUtils.getString(bySql.get(0),"iscenterstore");
            itemapplynum = MapUtils.getString(bySql.get(0),"itemapplynum");
        }
        //流程标识（子表单价是否有超过1万）1：不超过1万2：超过一万
        List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT a.unitcost,IF(a.subjectno like '%科研管理%','2','1') as subjectno from gq_itemapplyline a LEFT JOIN gq_itemapply b on a.glnum=b.itemapplynum where itemapplynum = '" + itemapplynum + "'");
        if(CollectionUtils.isNotEmpty(bySql1)){
            for (Map<String, Object> map : bySql1) {
                String unitcost = MapUtils.getString(map, "unitcost");
                BigDecimal bigDecimal = new BigDecimal("10000");
                BigDecimal unitcostBig = new BigDecimal(unitcost);
                if(unitcostBig.compareTo(bigDecimal)>0){
                    issonpricemany = "2";
                }

                //流程标识（子表课题号是否为科研课题号）1：不是科研课题好2：是科研课题号
                issonsubject  = MapUtils.getString(map,"subjectno");
            }
        }
        //流程标识（子表课题号是否为科研课题号）1：不是科研课题好2：是科研课题号


        //统一修改流程标识
        handlerService.findBySql("update gq_itemapply set iscenterstore = '" + iscenterstore + "', issonpricemany = '" + issonpricemany + "', issonsubject = '" + issonsubject + "' where id ='" + id + "'");
    }
}
